import {
  _decorator,
  Collider2D,
  Component,
  Contact2DType,
  IPhysics2DContact,
  RigidBody2D,
  Vec2,
  view,
} from "cc";
import { CollisionTag } from "./CollisionTag";
import { EnemyControl } from "./EnemyControl";
const { ccclass, property } = _decorator;

@ccclass("BulletControl")
export class BulletControl extends Component {
  speed = 20;

  // 碰到敌机的回调
  killEnemyCallback?: () => void;

  protected start(): void {
    const rigidBody2D = this.getComponent(RigidBody2D);
    rigidBody2D.linearVelocity = new Vec2(0, this.speed);

    // 注册单个碰撞体的回调函数
    const collider = this.getComponent(Collider2D);
    if (collider) {
      collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  protected update(dt: number): void {
    if (this._isOutView()) {
      this.node.destroy();
    }
  }

  /**
   * 是否超出屏幕
   * @returns {boolean}
   */
  private _isOutView(): boolean {
    return this.node.position.y > view.getDesignResolutionSize().height;
  }

  // 只在两个碰撞体开始接触时被调用一次
  onBeginContact(
    selfCollider: Collider2D,
    otherCollider: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    console.log("碰撞检测", otherCollider.tag);
    if (otherCollider.tag === CollisionTag.Enemy) {
      // 敌人死亡
      otherCollider.getComponent(EnemyControl).die();

      // 加分
      // ...
      console.log("碰到了敌人");
      this?.killEnemyCallback();

      // 不加延时会报错 You are trying to destroy a object twice or more.
      setTimeout(() => {
        // 子弹消失
        this.node && this.node.destroy();
      });
    }
  }
}
